package cn.stylefeng.guns.modular.emergency.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.consts.ProjectConstants;
import cn.stylefeng.guns.modular.emergency.entity.Emergency;
import cn.stylefeng.guns.modular.emergency.entity.EmergencyType;
import cn.stylefeng.guns.modular.emergency.mapper.EmergencyMapper;
import cn.stylefeng.guns.modular.emergency.mapper.EmergencyTypeMapper;
import cn.stylefeng.guns.modular.emergency.pojo.request.EmergencyTypeRequest;
import cn.stylefeng.guns.modular.emergency.pojo.response.TreeEmergencyTypeInfo;
import cn.stylefeng.guns.modular.emergency.service.EmergencyService;
import cn.stylefeng.guns.modular.emergency.service.EmergencyTypeService;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.guns.modular.emergency.entity.RelationLevel;
import cn.stylefeng.guns.modular.emergency.enums.RelationLevelExceptionEnum;
import cn.stylefeng.guns.modular.emergency.mapper.RelationLevelMapper;
import cn.stylefeng.guns.modular.emergency.pojo.request.RelationLevelRequest;
import cn.stylefeng.guns.modular.emergency.service.RelationLevelService;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.pojo.response.ErrorResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.rule.tree.factory.DefaultTreeBuildFactory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 应急预案类型层级业务实现层
 *
 * @author xbz
 * @date 2023/04/24 14:58
 */
@Service
public class RelationLevelServiceImpl extends ServiceImpl<RelationLevelMapper, RelationLevel> implements RelationLevelService {

    @Resource
    private EmergencyTypeService emergencyTypeService;

    @Resource
    private EmergencyTypeMapper emergencyTypeMapper;
    @Resource
    private EmergencyMapper emergencyMapper;

	@Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData addEmergencyTypeNode(RelationLevelRequest relationLevelRequest) {

        if (relationLevelRequest.getDirectParentTypeId()>0){
            LambdaQueryWrapper<RelationLevel> relationLevelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            relationLevelLambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(relationLevelRequest.getDirectParentTypeId()),RelationLevel::getId,relationLevelRequest.getDirectParentTypeId())
                    .eq(RelationLevel::getTableName,ProjectConstants.EPC_EMERGENCY_TYPE_TABLE_NAME);
            List<RelationLevel> relationLevelList = this.baseMapper.selectList(relationLevelLambdaQueryWrapper);
            if(!(relationLevelList == null || relationLevelList.isEmpty())){
                LambdaQueryWrapper<Emergency> emergencyLambdaQueryWrapper = new LambdaQueryWrapper<>();
                emergencyLambdaQueryWrapper.eq(Emergency::getCategoryId,relationLevelList.get(0).getDataId());
                List<Emergency> emergencyList = emergencyMapper.selectList(emergencyLambdaQueryWrapper);
                if(emergencyList == null || emergencyList.isEmpty()){
                    List<RelationLevel> list = new ArrayList<>();
                    EmergencyTypeRequest emergencyTypeRequest = new EmergencyTypeRequest();
                    emergencyTypeRequest.setCategoryName(relationLevelRequest.getCategoryName());
                    emergencyTypeRequest.setDelFlag("N");
                    emergencyTypeService.add(emergencyTypeRequest);

                    List<EmergencyType> typeList = emergencyTypeService.findList(emergencyTypeRequest);
                    for(RelationLevel relationLevel : relationLevelList){
                        RelationLevel level = new RelationLevel();
                        BeanUtil.copyProperties(relationLevelRequest, level);
                        level.setDataId(typeList.get(0).getId());
                        level.setRootStatus(0);
                        level.setParentsTypeId(relationLevel.getParentsTypeId());
                        level.setDelFlag("N");
                        level.setTableName(ProjectConstants.EPC_EMERGENCY_TYPE_TABLE_NAME);
                        list.add(level);
                    }
                    RelationLevel level2 = new RelationLevel();
                    level2.setDataId(typeList.get(0).getId());
                    level2.setRootStatus(0);
                    level2.setDirectParentTypeId(relationLevelRequest.getDirectParentTypeId());
                    level2.setParentsTypeId(relationLevelRequest.getDirectParentTypeId());
                    level2.setDelFlag("N");
                    level2.setTableName(ProjectConstants.EPC_EMERGENCY_TYPE_TABLE_NAME);
                    list.add(level2);
                    this.baseMapper.insertBatch(list);
                    return new SuccessResponseData("添加成功");
                }else{
                    return new ErrorResponseData("1001","该类别下已经有应急预案,不允许添加子类");
                }
            }else{
                return new ErrorResponseData("1001","没有该类别");
            }

        }else{
            EmergencyTypeRequest emergencyTypeRequest = new EmergencyTypeRequest();
            emergencyTypeRequest.setCategoryName(relationLevelRequest.getCategoryName());
            emergencyTypeRequest.setDelFlag("N");
            emergencyTypeService.add(emergencyTypeRequest);
            List<EmergencyType> typeList = emergencyTypeService.findList(emergencyTypeRequest);

            RelationLevel relationLevel = new RelationLevel();
            BeanUtil.copyProperties(relationLevelRequest, relationLevel);
            relationLevel.setDataId(typeList.get(0).getId());
            relationLevel.setRootStatus(1);
            relationLevel.setParentsTypeId(-1L);
            relationLevel.setDelFlag("N");
            relationLevel.setTableName(ProjectConstants.EPC_EMERGENCY_TYPE_TABLE_NAME);
            this.save(relationLevel);
            return new SuccessResponseData("添加成功");
        }



    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData delEmergencyTypeNode(RelationLevelRequest relationLevelRequest) {
       LambdaQueryWrapper<RelationLevel> relationLevelLambdaQueryWrapper = new LambdaQueryWrapper<>();
       relationLevelLambdaQueryWrapper.eq(RelationLevel::getDirectParentTypeId,relationLevelRequest.getId());
        List<RelationLevel> relationLevelList = this.baseMapper.selectList(relationLevelLambdaQueryWrapper);
        if(relationLevelList == null || relationLevelList.isEmpty()){
            LambdaQueryWrapper<Emergency> emergencyLambdaQueryWrapper = new LambdaQueryWrapper<>();
            emergencyLambdaQueryWrapper.eq(Emergency::getCategoryId,relationLevelRequest.getDataId());
            List<Emergency> emergencyList = emergencyMapper.selectList(emergencyLambdaQueryWrapper);
            if(emergencyList == null || emergencyList.isEmpty()){
                emergencyLambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(relationLevelRequest.getDataId()),Emergency::getCategoryId,relationLevelRequest.getDataId());
                emergencyMapper.selectList(emergencyLambdaQueryWrapper);
                relationLevelLambdaQueryWrapper.clear();
                relationLevelLambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(relationLevelRequest.getDataId()),RelationLevel::getDataId,relationLevelRequest.getDataId())
                        .eq(RelationLevel::getTableName,ProjectConstants.EPC_EMERGENCY_TYPE_TABLE_NAME);
                List<RelationLevel> relationLevels = this.baseMapper.selectList(relationLevelLambdaQueryWrapper);
//                List<Long> idList = relationLevels.stream().map(RelationLevel::getId).collect(Collectors.toList());
                RelationLevel relationLevel = new RelationLevel();
                relationLevel.setDelFlag("Y");
                this.baseMapper.update(relationLevel,relationLevelLambdaQueryWrapper);
                EmergencyType emergencyType = new EmergencyType();
                emergencyType.setId(relationLevelRequest.getDataId());
                emergencyType.setDelFlag("Y");
                emergencyTypeMapper.updateById(emergencyType);
//                this.baseMapper.deleteBatchIds(idList);
//                emergencyTypeMapper.deleteById(relationLevelRequest.getDataId());
                return new SuccessResponseData("删除成功");
            }else{
                return new ErrorResponseData("1001","该类别下有应急预案,不允许删除");
            }

        }else {
            return new ErrorResponseData("1001","该类别下有子类,不允许删除");
        }
    }

    @Override
    public void edit(RelationLevelRequest relationLevelRequest) {
        RelationLevel relationLevel = this.queryRelationLevel(relationLevelRequest);
        BeanUtil.copyProperties(relationLevelRequest, relationLevel);
        this.updateById(relationLevel);
    }

    @Override
    public RelationLevel detail(RelationLevelRequest relationLevelRequest) {
        return this.queryRelationLevel(relationLevelRequest);
    }

    @Override
    public PageResult<RelationLevel> findPage(RelationLevelRequest relationLevelRequest) {
        LambdaQueryWrapper<RelationLevel> wrapper = createWrapper(relationLevelRequest);
        Page<RelationLevel> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }


    @Override
    public List<RelationLevel> findList(RelationLevelRequest relationLevelRequest) {
        LambdaQueryWrapper<RelationLevel> wrapper = this.createWrapper(relationLevelRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author xbz
     * @date 2023/04/24 14:58
     */
    private RelationLevel queryRelationLevel(RelationLevelRequest relationLevelRequest) {
        RelationLevel relationLevel = this.getById(relationLevelRequest.getId());
        if (ObjectUtil.isEmpty(relationLevel)) {
            throw new ServiceException(RelationLevelExceptionEnum.RELATION_LEVEL_NOT_EXISTED);
        }
        return relationLevel;
    }

    /**
     * 创建查询wrapper
     *
     * @author xbz
     * @date 2023/04/24 14:58
     */
    private LambdaQueryWrapper<RelationLevel> createWrapper(RelationLevelRequest relationLevelRequest) {
        LambdaQueryWrapper<RelationLevel> queryWrapper = new LambdaQueryWrapper<>();

        Long id = relationLevelRequest.getId();
        Long dataId = relationLevelRequest.getDataId();
        Integer rootStatus = relationLevelRequest.getRootStatus();
        Long directParentTypeId = relationLevelRequest.getDirectParentTypeId();
        Long parentsTypeId = relationLevelRequest.getParentsTypeId();
        Integer level = relationLevelRequest.getLevel();
        String delFlag = relationLevelRequest.getDelFlag();
        String tableName = relationLevelRequest.getTableName();

        queryWrapper.eq(ObjectUtil.isNotNull(id), RelationLevel::getId, id);
        queryWrapper.eq(ObjectUtil.isNotNull(dataId), RelationLevel::getDataId, dataId);
        queryWrapper.eq(ObjectUtil.isNotNull(rootStatus), RelationLevel::getRootStatus, rootStatus);
        queryWrapper.eq(ObjectUtil.isNotNull(directParentTypeId), RelationLevel::getDirectParentTypeId, directParentTypeId);
        queryWrapper.eq(ObjectUtil.isNotNull(parentsTypeId), RelationLevel::getParentsTypeId, parentsTypeId);
        queryWrapper.eq(ObjectUtil.isNotNull(level), RelationLevel::getLevel, level);
        queryWrapper.like(ObjectUtil.isNotEmpty(delFlag), RelationLevel::getDelFlag, delFlag);
        queryWrapper.like(ObjectUtil.isNotEmpty(tableName), RelationLevel::getTableName, tableName);

        return queryWrapper;
    }

}